// 导出
const ExportJsonExcel = require('js-export-excel')

export function handleExportExcel(config, toSave = true) {
  const ExportConfig = {
    fileName: '表格',
    sheetData: null,
    sheetFilter: null,
    sheetHeader: null,
    pctArrKeys: null,
    ...config
  }
  if (!ExportConfig.sheetData) {
    throw new Error('导出数据不能为空')
  }

  const option = {
    fileName: ExportConfig.fileName + (new Date()).getTime()
  }
  if (config.fixedName) {
    option.fileName = ExportConfig.fileName
  }
  const sheetData = formatData(ExportConfig.sheetData, ExportConfig.pctArrKeys)

  if (!toSave) {
    option.saveAsBlob = true
  }

  option.datas = [
    {
      sheetData,
      sheetName: '表格', // Excel文件sheel名称
      sheetFilter: ExportConfig.sheetFilter ? ExportConfig.sheetFilter : Object.keys(ExportConfig.sheetData[0]),
      sheetHeader: ExportConfig.sheetHeader ? ExportConfig.sheetHeader : Object.keys(ExportConfig.sheetData[0]),
      columnWidths: ExportConfig.sheetHeader ? ExportConfig.sheetHeader.map(() => 10) : Object.keys(ExportConfig.sheetData[0]).map(() => 10)
    }
  ]
  const toExcel = new ExportJsonExcel(option)
  if (toSave) {
    toExcel.saveExcel()
  } else {
    return toExcel.saveExcel()
  }
}

function formatData(data, pctArrKeys) {
  if (!data && !data.length) return
  const newData = JSON.parse(JSON.stringify(data))
  for (const o of newData) {
    if (pctArrKeys && pctArrKeys.length > 0) {
      pctArrKeys.map(itemKey => {
        o[itemKey] = `${(o[itemKey] * 100).toFixed(2)}%`
      })
    }
  }
  return newData
}

export default handleExportExcel
